import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/core/utils/device_utils.dart';
import 'package:casdon/core/utils/first_launch_service.dart';
import 'package:flutter/material.dart';

/// 引导页覆盖层组件
class GuideOverlayWidget extends StatefulWidget {
  final Widget child;
  const GuideOverlayWidget({super.key, required this.child});

  @override
  State<GuideOverlayWidget> createState() => _GuideOverlayWidgetState();
}

class _GuideOverlayWidgetState extends State<GuideOverlayWidget> {
  int _currentStep = 0; // 0, 1, 2 对应 guid1, guid2, guid3
  bool _showGuide = false;
  bool _isSE = false;

  @override
  void initState() {
    super.initState();
    DeviceInfoManager.isiPhoneSE().then((val) {
      if (mounted) setState(() => _isSE = val);
    });
    _checkAndShowGuide();
  }

  Future<void> _checkAndShowGuide() async {
    final shouldShow = await FirstLaunchService.instance
        .shouldShowGuideOverlay();

    if (shouldShow && mounted) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        setState(() {
          _showGuide = true;
        });
      });
    }
  }

  void _nextStep() {
    if (_currentStep < 2) {
      setState(() {
        _currentStep++;
      });
    } else {
      _completeGuide();
    }
  }

  Future<void> _completeGuide() async {
    await FirstLaunchService.instance.markGuideOverlayShown();
    if (mounted) {
      setState(() {
        _showGuide = false;
      });
    }
  }

  String _getGuideImagePath() {
    switch (_currentStep) {
      case 0:
        if (_isSE) {
          return Assets.images.guidse1.path;
        } else {
          return Assets.images.guid1.path;
        }

      case 1:
        if (_isSE) {
          return Assets.images.guidse2.path;
        } else {
          return Assets.images.guid2.path;
        }
      case 2:
        if (_isSE) {
          return Assets.images.guidse3.path;
        } else {
          return Assets.images.guid3.path;
        }
      default:
        return Assets.images.guid1.path;
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!_showGuide) {
      return widget.child;
    }

    return Stack(
      children: [
        widget.child,
        // 全屏引导页覆盖层（半透明）
        GestureDetector(
          onTap: _nextStep,
          child: Container(
            color: Colors.black.withOpacity(0.5), // 半透明黑色背景
            width: double.infinity,
            height: double.infinity,
            child: Image.asset(
              _getGuideImagePath(),
              fit: BoxFit.cover,
              width: double.infinity,
              height: double.infinity,
            ),
          ),
        ),
      ],
    );
  }
}
